// 导入Gitee工具类
import { SyncService } from './service/syncService.js';
import { NotificationsUtils } from './utils/notificationsUtils.js';
import { GiteeUtils } from './utils/giteeUtils.js';


// 初始化服务类实例
const syncService = new SyncService();
const notificationsUtils = new NotificationsUtils(); 
const giteeUtils = new GiteeUtils();

// 更新进度条显示
function updateProgressBar(percent) {
  const progressBar = document.getElementById('progressBar');
  const progressBarDiv = document.getElementById('progressBarDiv');
  if (progressBar) {
    if(percent == 0) {
      progressBarDiv.style.display = 'none';
    } else {
      progressBarDiv.style.display = 'block';
    }
    
    progressBar.style.width = percent + '%';
  }
}

function setProgressBarInterval(progress = 9, step = 15, max = 99, intervalMs = 300) {
  let interval = setInterval(() => {
      if (progress >= max) {
        clearInterval(interval);
      } else {
        progress += step;
        updateProgressBar(progress);
      }
    }, intervalMs);
    return interval;
}

function stopProgressBarInterval(interval, delayMs = 1500){
  updateProgressBar(100);
    clearInterval(interval);
    setTimeout(() => {updateProgressBar(0);}, delayMs);
}


// 从远程导入
document.getElementById('importBtn').addEventListener('click', async () => {
  let interval = null;
  try {
    interval = setProgressBarInterval();
    
    await syncService.importBookmarksFromRemote();
  } finally { 
    stopProgressBarInterval(interval);
  }
   
});
// 清除现有书签
document.getElementById('removeAllBtn').addEventListener('click', async() => {
  try {
    await syncService.removeAll();
  } finally {
  }
});

// 同步书签
document.getElementById('syncBtn').addEventListener('click', async () => {
  let interval = null;
   try {
    interval = setProgressBarInterval();
     await syncService.exportBookmarksToRemote();
   } finally { 
    stopProgressBarInterval(interval);
   }
});


// 切换到设置页面
document.getElementById('openSettings').addEventListener('click', () => {
  switch2Setting();
});

function switch2Setting() {
    document.getElementById('mainPage').classList.remove('active');
    document.getElementById('settingsPage').classList.add('active');
}

// 返回主页面
document.getElementById('cancelSettings').addEventListener('click', () => {
  switch2Main();
});

function switch2Main() {
  document.getElementById('settingsPage').classList.remove('active');
  document.getElementById('mainPage').classList.add('active');
}

// 保存设置并返回主页面
document.getElementById('saveSettings').addEventListener('click', () => {
  const settings = {
    token: document.getElementById('token').value,
    repoName: document.getElementById('repoName').value,
    fileName: document.getElementById('fileName').value,
    autoSync: document.getElementById('autoSyncCheckbox').checked
  };
  chrome.storage.local.set(settings, () => {
    syncService.loadStoredConfig();
    notificationsUtils.showMsg('设置保存成功');
    switch2Main();
  });
});


// 跳转到获取token的页面
document.getElementById('getTokenBtn').addEventListener('click', () => {
    chrome.tabs.create({ url: 'https://gitee.com/profile/personal_access_tokens' });
});

// 获取历史记录
document.getElementById('historyBtn').addEventListener('click', async () => {
  chrome.storage.local.get(['repoName', 'token', 'fileName'], (result) => {
    giteeUtils.getUser(result.token).then(owner => {
      giteeUtils.getHisList(owner, result.repoName, result.token).then(data => {
      if (!Array.isArray(data)) {
        notificationsUtils.showMsg('数据格式错误');
        return;
      }

      // 创建对话框元素
      const dialog = document.createElement('div');
      dialog.style.position = 'fixed';
      dialog.style.top = '50%';
      dialog.style.left = '50%';
      dialog.style.width = '80%';
      dialog.style.height = '70%';
      dialog.style.transform = 'translate(-50%, -50%)';
      dialog.style.backgroundColor = 'white';
      dialog.style.padding = '20px';
      dialog.style.boxShadow = '0 4px 8px rgba(0,0,0,0.1)';
      dialog.style.zIndex = '1000';
      dialog.style.borderRadius = '8px';
      
      // 添加标题
      const title = document.createElement('h2');
      title.textContent = '导入历史';
      title.style.marginTop = '0';
      dialog.appendChild(title);

      // 创建下拉框
      const select = document.createElement('select');
      select.style.marginBottom = '10px';
      select.style.padding = '5px';
      select.style.width = '100%';

      // 填充下拉框选项
      data.forEach(item => {
        const option = document.createElement('option');
        option.value = item.name;
        option.textContent = item.name;
        select.appendChild(option);
      });

      // 创建按钮容器
      const buttonContainer = document.createElement('div');
      buttonContainer.style.display = 'flex';
      buttonContainer.style.justifyContent = 'space-between';

      // 创建确认按钮
      const confirmBtn = document.createElement('button');
      confirmBtn.textContent = '确认';
      confirmBtn.style.padding = '5px 10px';
      confirmBtn.style.cursor = 'pointer';

      // 创建取消按钮
      const cancelBtn = document.createElement('button');
      cancelBtn.textContent = '取消';
      cancelBtn.style.padding = '5px 10px';
      cancelBtn.style.cursor = 'pointer';

      // 添加按钮事件
      confirmBtn.addEventListener('click', async () => {
        console.log('Selected his fileName:', select.value);
        const result = syncService.importBookmarksFromRemote(select.value);
        if(result) {
          document.body.removeChild(dialog);
        }
        
      });

      cancelBtn.addEventListener('click', () => {
        document.body.removeChild(dialog);
      });

      // 组装对话框
      buttonContainer.appendChild(confirmBtn);
      buttonContainer.appendChild(cancelBtn);

      dialog.appendChild(select);
      dialog.appendChild(buttonContainer);

      // 添加到页面
      document.body.appendChild(dialog);
      });
    });

  });

});

// 切换高级设置面板的显示状态
document.getElementById('toggleAdvanced').addEventListener('click', () => {

  const advancedSettings = document.querySelector('.advanced-settings');
  const isHidden = advancedSettings.style.maxHeight === '0px' || advancedSettings.style.maxHeight === '';
  
  advancedSettings.style.maxHeight = isHidden ? '200px' : '0px';
  event.target.textContent = isHidden ? '隐藏高级设置' : '显示高级设置';
});


// 默认的Git设置
const defaultGitSettings = {
  token: '',
  repoName: 'chrome_syn_250724',
  fileName: 'sync_main.json'
};

// 填充输入框并监听变化
document.addEventListener('DOMContentLoaded', () => {
  // 设置默认值或从存储中读取
  chrome.storage.local.get(['token', 'repoName', 'fileName','autoSync'], (result) => {
    document.getElementById('token').value = result.token || defaultGitSettings.token;
    document.getElementById('repoName').value = result.repoName || defaultGitSettings.repoName;
    document.getElementById('fileName').value = result.fileName || defaultGitSettings.fileName;
    document.getElementById('autoSyncCheckbox').checked = result.autoSync !== false; // 默认为true
  });
  
 
});